<template>
  <div class="video-list-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>教学视频管理</span>
          <el-button type="primary" @click="showAddVideoDialog">新增视频</el-button>
        </div>
      </template>
      
      <!-- 搜索和筛选 -->
      <div class="search-filter">
        <el-input v-model="searchQuery" placeholder="搜索视频标题" prefix-icon="Search" style="width: 300px; margin-right: 15px;"></el-input>
        <el-select v-model="selectedCategory" placeholder="选择视频分类" style="width: 200px; margin-right: 15px;">
          <el-option label="全部" value=""></el-option>
          <el-option label="运动教学" value="exercise"></el-option>
          <el-option label="鼻炎护理" value="rhinitis"></el-option>
          <el-option label="健康讲座" value="lecture"></el-option>
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
      
      <!-- 视频表格 -->
      <el-table :data="videosData" style="width: 100%">
        <el-table-column prop="id" label="视频ID" width="80"></el-table-column>
        <el-table-column label="封面图" width="120">
          <template #default="scope">
            <el-image :src="scope.row.coverUrl" :preview-src-list="[scope.row.coverUrl]" style="width: 100px; height: 60px; object-fit: cover;"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="视频标题" min-width="200">
          <template #default="scope">
            <div class="title-preview" :title="scope.row.title">
              {{ scope.row.title }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="视频分类" width="120">
          <template #default="scope">
            <el-tag :type="getCategoryType(scope.row.category)">
              {{ getCategoryName(scope.row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="视频时长" width="100"></el-table-column>
        <el-table-column prop="playCount" label="播放量" width="100"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'published' ? 'success' : 'warning'">
              {{ scope.row.status === 'published' ? '已发布' : '草稿' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button type="primary" size="small" @click="showEditVideoDialog(scope.row)">编辑</el-button>
            <el-button :type="scope.row.status === 'published' ? 'warning' : 'success'" size="small" @click="handleToggleStatus(scope.row)">
              {{ scope.row.status === 'published' ? '下架' : '发布' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
    
    <!-- 新增/编辑视频对话框 -->
    <el-dialog v-model="videoDialogVisible" :title="dialogTitle" width="800px">
      <el-form :model="videoForm" :rules="videoRules" ref="videoFormRef" label-width="120px">
        <el-form-item label="视频标题" prop="title">
          <el-input v-model="videoForm.title" placeholder="请输入视频标题"></el-input>
        </el-form-item>
        <el-form-item label="视频分类" prop="category">
          <el-select v-model="videoForm.category" placeholder="请选择视频分类">
            <el-option label="运动教学" value="exercise"></el-option>
            <el-option label="鼻炎护理" value="rhinitis"></el-option>
            <el-option label="健康讲座" value="lecture"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="视频链接" prop="videoUrl">
          <el-input v-model="videoForm.videoUrl" placeholder="请输入视频链接"></el-input>
        </el-form-item>
        <el-form-item label="封面图链接" prop="coverUrl">
          <el-input v-model="videoForm.coverUrl" placeholder="请输入封面图链接"></el-input>
        </el-form-item>
        <el-form-item label="视频时长" prop="duration">
          <el-input v-model="videoForm.duration" placeholder="请输入视频时长(如：05:30)"></el-input>
        </el-form-item>
        <el-form-item label="视频简介" prop="description">
          <el-input v-model="videoForm.description" type="textarea" :rows="3" placeholder="请输入视频简介"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="videoForm.status" active-value="published" inactive-value="draft"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="videoDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveVideo">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// 搜索和筛选条件
const searchQuery = ref('')
const selectedCategory = ref('')

// 表格数据
const videosData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)

// 对话框状态
const videoDialogVisible = ref(false)
const editingVideoId = ref(null)
const videoFormRef = ref()

// 视频表单
const videoForm = reactive({
  title: '',
  category: '',
  videoUrl: '',
  coverUrl: '',
  duration: '',
  description: '',
  status: 'draft'
})

// 表单验证规则
const videoRules = {
  title: [
    { required: true, message: '请输入视频标题', trigger: 'blur' },
    { min: 5, max: 200, message: '视频标题长度在 5 到 200 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择视频分类', trigger: 'change' }
  ],
  videoUrl: [
    { required: true, message: '请输入视频链接', trigger: 'blur' }
  ],
  coverUrl: [
    { required: true, message: '请输入封面图链接', trigger: 'blur' }
  ],
  duration: [
    { required: true, message: '请输入视频时长', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入视频简介', trigger: 'blur' },
    { min: 10, max: 500, message: '视频简介长度在 10 到 500 个字符', trigger: 'blur' }
  ]
}

// 对话框标题
const dialogTitle = computed(() => {
  return editingVideoId.value ? '编辑视频' : '新增视频'
})

// 获取分类标签类型
const getCategoryType = (category) => {
  const typeMap = {
    'exercise': 'success',
    'rhinitis': 'warning',
    'lecture': 'info'
  }
  return typeMap[category] || 'primary'
}

// 获取分类名称
const getCategoryName = (category) => {
  const nameMap = {
    'exercise': '运动教学',
    'rhinitis': '鼻炎护理',
    'lecture': '健康讲座'
  }
  return nameMap[category] || category
}

// 获取视频列表
const fetchVideos = () => {
  // 实际项目中应该从后端获取数据
  // 这里使用模拟数据
  const mockData = [
    {
      id: 1,
      title: '提肛运动标准动作教学',
      category: 'exercise',
      videoUrl: '#',
      coverUrl: 'https://picsum.photos/400/240?random=1',
      duration: '03:45',
      playCount: 1250,
      status: 'published',
      createdAt: '2023-07-01 10:00:00'
    },
    {
      id: 2,
      title: '鼻炎日常护理方法演示',
      category: 'rhinitis',
      videoUrl: '#',
      coverUrl: 'https://picsum.photos/400/240?random=2',
      duration: '05:20',
      playCount: 980,
      status: 'published',
      createdAt: '2023-07-02 11:00:00'
    },
    {
      id: 3,
      title: '中医养生健康讲座',
      category: 'lecture',
      videoUrl: '#',
      coverUrl: 'https://picsum.photos/400/240?random=3',
      duration: '15:30',
      playCount: 850,
      status: 'published',
      createdAt: '2023-07-03 12:00:00'
    }
  ]
  
  // 应用搜索和筛选
  let filteredData = [...mockData]
  if (searchQuery.value) {
    filteredData = filteredData.filter(video => 
      video.title.includes(searchQuery.value)
    )
  }
  if (selectedCategory.value) {
    filteredData = filteredData.filter(video => video.category === selectedCategory.value)
  }
  
  total.value = filteredData.length
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  videosData.value = filteredData.slice(start, end)
}

// 显示新增视频对话框
const showAddVideoDialog = () => {
  editingVideoId.value = null
  // 重置表单
  if (videoFormRef.value) {
    videoFormRef.value.resetFields()
  }
  // 重置表单数据
  videoForm.title = ''
  videoForm.category = ''
  videoForm.videoUrl = ''
  videoForm.coverUrl = ''
  videoForm.duration = ''
  videoForm.description = ''
  videoForm.status = 'draft'
  videoDialogVisible.value = true
}

// 显示编辑视频对话框
const showEditVideoDialog = (video) => {
  editingVideoId.value = video.id
  videoForm.id = video.id
  videoForm.title = video.title
  videoForm.category = video.category
  videoForm.videoUrl = video.videoUrl
  videoForm.coverUrl = video.coverUrl
  videoForm.duration = video.duration
  videoForm.description = video.description || ''
  videoForm.status = video.status
  videoDialogVisible.value = true
}

// 保存视频
const handleSaveVideo = () => {
  videoFormRef.value.validate((valid) => {
    if (valid) {
      // 实际项目中应该调用API保存数据
      ElMessage.success(editingVideoId.value ? '视频编辑成功' : '视频新增成功')
      videoDialogVisible.value = false
      fetchVideos()
    }
  })
}

// 切换视频状态
const handleToggleStatus = (video) => {
  const newStatus = video.status === 'published' ? 'draft' : 'published'
  // 实际项目中应该调用API更新状态
  ElMessage.success(`视频已${newStatus === 'published' ? '发布' : '下架'}`)
  fetchVideos()
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchVideos()
}

// 重置搜索
const resetSearch = () => {
  searchQuery.value = ''
  selectedCategory.value = ''
  currentPage.value = 1
  fetchVideos()
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchVideos()
}

const handleCurrentChange = (current) => {
  currentPage.value = current
  fetchVideos()
}

// 初始化数据
fetchVideos()
</script>

<style scoped>
.video-list-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-filter {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.title-preview {
  word-break: break-word;
  color: #303133;
}
</style>